package org.ragdollcat.secondaiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

/**
 * 自定义日志拦截器
 */
@Slf4j
public class MyLogAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {


    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        //前置增强
        log.info("自定义日志拦截器，AI request:{}",advisedRequest.userText());
        //调用下一个拦截器
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        //后置增强
        log.info("自定义日志拦截器，AI response:{}",advisedResponse.response().getResult().getOutput().getText());
        return advisedResponse;
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        //前置增强
        log.info("自定义日志拦截器，AI request:{}",advisedRequest.userText());
        Flux<AdvisedResponse> advisedResponseFlux = chain.nextAroundStream(advisedRequest);
        return new MessageAggregator().aggregateAdvisedResponse(advisedResponseFlux, new Consumer<AdvisedResponse>() {
            @Override
            public void accept(AdvisedResponse advisedResponse) {
                //后置增强
                log.info("自定义日志拦截器，AI response:{}",advisedResponse.response().getResult().getOutput().getText());
            }
        });
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
